package net.shopxx.dao.impl;

import java.util.Map.Entry;

import net.shopxx.bean.Pager;
import net.shopxx.dao.ProductConsultDao;
import net.shopxx.entity.Member;
import net.shopxx.entity.Product;
import net.shopxx.entity.ProductConsult;

import org.hibernate.Query;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

/**
 * Dao实现类 - 订单项
 */

@Repository
public class ProductConsultDaoImpl extends BaseDaoImpl<ProductConsult, String> implements ProductConsultDao {

	@Override
	public Pager getMemberConsultPager(Member member, Pager pager) {
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(ProductConsult.class);
		detachedCriteria.createAlias("member", "member");
		detachedCriteria.add(Restrictions.eq("member.id", member.getId()));
//		detachedCriteria.addOrder(Order.desc("name"));
		return findByPager(pager, detachedCriteria);
	}

	@Override
	public Pager getProductConsultPager(Product product, Pager pager) {
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(ProductConsult.class);
		detachedCriteria.createAlias("product", "product");
		detachedCriteria.add(Restrictions.eq("product.id", product.getId()));
//		detachedCriteria.addOrder(Order.desc("name"));
		return findByPager(pager, detachedCriteria);
	}

	@Override
	public Pager getMemberOwnConsultPager(Member member, Pager pager) {
		
		if(pager==null)
		{
			pager = new Pager();
		}
		Integer pageNumber = pager.getPageNumber();
		Integer pageSize = pager.getPageSize();
		String hql = "select pc from ProductConsult as pc inner join pc.product as p with p.member.id=? where 1=1 ";
		if(!pager.getWhereClause().isEmpty())
		{
			for (String key : pager.getWhereClause().keySet()) {
				hql += " and "+key+"=? ";
			}
		}
		
		int i=0;
		
		Query query = getSession().createQuery(hql).setParameter(i++, member.getId());
		if(!pager.getWhereClause().isEmpty())
		{
			for (String key : pager.getWhereClause().keySet()) {
				query.setParameter(i++, pager.getWhereClause().get(key));
			}
		}
		pager.setTotalCount(query.list().size());
		query.setFirstResult((pageNumber - 1) * pageSize);
		query.setMaxResults(pageSize);
		pager.setList(query.list());
		return pager;
	}
	
}